package com.zch.zhongchou.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alibaba.fastjson.JSONObject;
import com.zch.zhongchou.pojo.NewUser;
import com.zch.zhongchou.pojo.Projects;
import com.zch.zhongchou.pojo.User;
import com.zch.zhongchou.service.UserService;
import com.zch.zhongchou.util.MailUtil;
import com.zch.zhongchou.util.PhoneUtil;

@Controller
@RequestMapping("UserController")
public class UserController {
	@Autowired
	private UserService us;
	//引用user实体类
	private User user = null;
	@RequestMapping("login1")
	public void login(String phoneOrEmail,String password,HttpServletResponse response,
			HttpServletRequest request) throws Exception{
		Map<String, Object> map = us.login(phoneOrEmail, password);
		boolean flag = (boolean) map.get("isLogin");
		PrintWriter out = response.getWriter();
		HttpSession session = request.getSession();
		if(flag){
			session.setAttribute("user1", map.get("user1"));
			String a = URLEncoder.encode("登陆成功", "UTF-8");
			out.println("<script language='javascript'>alert(decodeURIComponent('"+a+"'));window.location.href='../index.jsp'</script>");
		}else{
			String a = URLEncoder.encode((String)map.get("msg"), "UTF-8");
			out.println("<script language='javascript'>alert(decodeURIComponent('"+a+"'));window.location.href='../login.jsp'</script>");
		}
	}
	
	@RequestMapping("intoUser")
	public String intoUser(int usId,HttpServletRequest request){
		//根据usId获得该用户的所有项目列表
		List<Projects> list = us.getProjectsByusId(usId);
		request.setAttribute("list", list);
		return "user";
	}
	//添加用户
	@RequestMapping(value="addUser",method=RequestMethod.POST)
	public void addUser(String phoneOrEmail,String usName,String password,String code,
			HttpServletResponse response) throws Exception{
		User user = new User();
		user.setUsName(usName);
		user.setUsPassword(password);
		user.setUsCode(code);
		//邮箱正则表达式
		String expr = "^\\w+@(\\w+\\.)+\\w+$";
		if(phoneOrEmail.matches(expr)){
			user.setUsEmail(phoneOrEmail);
		}
		//手机正则表达式
		String expr2 = "^(13[0-9]|15[0-9]|153|15[6-9]|180|18[23]|18[5-9])\\d{8}$";
		Pattern pattern = Pattern.compile(expr2);
		Matcher matcher = pattern.matcher(phoneOrEmail);
		System.out.println(matcher.matches());
		if(matcher.matches()){
			user.setUsPhone(phoneOrEmail);
		}
		//向数据库中添加用户信息
		int flag = us.add(user);
		PrintWriter out = response.getWriter();
		if(flag>0){
			String a = URLEncoder.encode("添加成功", "UTF-8");
			out.println("<script language='javascript'>alert(decodeURIComponent('"+a+"'));window.location.href='../index.jsp'</script>");
		}else{
			String a = URLEncoder.encode("添加失败", "UTF-8");
			out.println("<script language='javascript'>alert(decodeURIComponent('"+a+"'));window.location.href='../login.jsp'</script>");
		}
		
	}
	//获取验证码和手机或邮箱
	@RequestMapping(value="getValide",method=RequestMethod.POST)
	public void getValide(@RequestBody NewUser nUser ,HttpServletResponse response) throws Exception{
		System.out.println(nUser);
		PrintWriter out = response.getWriter();
		//将传入前台的数据转换为json格式的 
		JSONObject jsonObj = new JSONObject();
		jsonObj.put("result", true);
		//判断是邮箱还是手机号
		//邮箱正则表达式
		String expr = "^\\w+@(\\w+\\.)+\\w+$";
		if(nUser.getPhoneOrEmail().matches(expr)){
			//执行向邮箱发送验证码
			new Thread(new MailUtil(nUser.getPhoneOrEmail(), nUser.getCode())).start();
			System.out.println("成功发送验证码到邮箱-"+nUser.getPhoneOrEmail());
			out.print(jsonObj.toString());
		}
		
		//手机正则表达式
		String expr2 = "^(13[0-9]|15[0-9]|153|15[6-9]|180|18[23]|18[5-9])\\d{8}$";
		Pattern pattern = Pattern.compile(expr2);
		Matcher matcher = pattern.matcher(nUser.getPhoneOrEmail());
		if(matcher.matches()){
			//执行向手机号发送验证码
			if(PhoneUtil.sendCode(nUser.getPhoneOrEmail(), nUser.getCode())){
				System.out.println("成功发送验证码到手机-"+nUser.getPhoneOrEmail());
				out.print(jsonObj.toString());
			}
		}
	}
	
	@RequestMapping("outUser")
	public String doOut(HttpServletRequest request){
		HttpSession session = request.getSession();
		session.removeAttribute("user1");
		return "redirect:toIndex";
	}
	@RequestMapping("toIndex")
	public String toIndex(){
		return "/index";
	}
	
	//修改密码，根据邮箱或手机号获得用户信息，并存入user成员属性中
	@RequestMapping("getUserByEmailOrPhone")
	public String getUserByEmailOrPhone(String phoneOrEmail,HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		System.out.println(phoneOrEmail);
		//HttpSession session = request.getSession();
		//PrintWriter out = response.getWriter();
		//获取用户信息
		user = us.getUserByName(phoneOrEmail);
		//System.out.println("user="+user);
		//存入修改密码的 对象
		//session.setAttribute("user2", user);
		return "updatepwd";
	}
	//异步刷新之实现用户注册邮箱不重复
	@RequestMapping("getUserByEmailOrPhone2")
	public void getUserByEmailOrPhone2(String phoneOrEmail,HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		System.out.println(phoneOrEmail);
		PrintWriter out = response.getWriter();
		//获取用户信息
		user = us.getUserByName(phoneOrEmail);
		System.out.println(user);
		if(user == null){
			//out.println("ok");//返回页面时接收到的数据是 内容+换行符
			out.print("ok");
		}else{
			out.print("no");
		}
	}
	//异步刷新之实现用户忘记密码并修改时判断邮箱或手机号是否存在
	@RequestMapping("getUserByEmailOrPhone3")
	public void getUserByEmailOrPhone3(String phoneOrEmail,HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		//System.out.println(phoneOrEmail);
		PrintWriter out = response.getWriter();
		//获取用户信息
		user = us.getUserByName(phoneOrEmail);
		if(user == null){
			out.print("on");
		}else{
			out.print("ok");
		}
	}
	
	//修改用户密码
	@RequestMapping("updatePwdOfUser")
	public void updatePwdOfUser(String password,HttpServletResponse response,HttpServletRequest request) throws Exception{
		PrintWriter out = response.getWriter();
		//HttpSession session = request.getSession();
		
		//获得存在session中的需要修改的用户对象
		//User user = (User) session.getAttribute("user2");
		//System.out.println(user);
		//修改密码
		user.setUsPassword(password);
		int flag = us.update(user);
		if(flag>0){
			String a = URLEncoder.encode("修改成功", "UTF-8");
			out.println("<script language='javascript'>alert(decodeURIComponent('"+a+"'));window.location.href='../login.jsp'</script>");
		}else{
			String a = URLEncoder.encode("修改失败", "UTF-8");
			out.println("<script language='javascript'>alert(decodeURIComponent('"+a+"'));window.location.href='../index.jsp'</script>");
		}
	}
	
	
	//更新用户信息
	@RequestMapping("updateUser")
	public void updateUser(User user,HttpServletResponse response) throws Exception{
		PrintWriter out = response.getWriter();
		//更新用户信息
		int flag = us.update(user);
		System.out.println(user);
		if(flag>0){
			String a = URLEncoder.encode("保存成功", "UTF-8");
			out.println("<script language='javascript'>alert(decodeURIComponent('"+a+"'));window.location.href='../user.jsp'</script>");
		}else{
			String a = URLEncoder.encode("保存失败", "UTF-8");
			out.println("<script language='javascript'>alert(decodeURIComponent('"+a+"'));window.location.href='../updateUser.jsp'</script>");
		}
	}
	
	//根据id获取用户信息
	@RequestMapping("getUserById")
	public String getUserById(int id,HttpServletRequest request){
		User user = us.getUserById(id);
		request.setAttribute("user", user);
		//System.out.println(user);
		return "updateUser";
	}
	
	public static void main(String[] args) {
		String a,b,c = "我爱你";
//		System.out.println("a="+a);//不能和变量c一同初始化
//		System.out.println("b="+b);//不能和变量c一同初始化
		System.out.println("c="+c);
	}
	
	
	
	
	
	
	
	
	
}
